
import { useEffect, useState } from 'react';
import { useResize } from '@/views/hooks/useResize';
import { getFieldConfig, getAfterSalesList, updateFieldConfig, getAfterSalesListById } from './services';
import { findIndex } from 'lodash';
import { Alert } from 'antd';
import SearchContent from './SearchContent/index';
import HeaderActions from './HeaderActions/index';
import RightAction from './RightAction/index';
import TableList from './TableList';
import CommonPagination from '@/components/CommonPagination';
import CommonLoading from '@/components/CommonLoading';
import { initColumns } from './config/index';
import styles from './index.module.less';
import { useLocation, useNavigate } from 'react-router-dom';

//页面存储的pagecode
const pageCode = "aftersalesOrderPageConfig";

//订单列表
const SalesOrder = (props) => {

	const [ formData, setFormData ] = useState({});

	//表格顶部右侧排序
	const [orderBy, setOrderBy] = useState('applyTime');

	//列表数据
	const [tableList, setTableList] = useState([]);

	const [loading, setLoading] = useState(false);

	//当前选中的key
	const [selectKeys, setselectKeys] = useState([]);

	const [pageConfig, setPageConfig] = useState({
		columns: initColumns,//订单列数据
	})

	//列表分页
	const [pages, setPages] = useState({
		current: 1,
		total: 0,
		pageSize: 500,
		pageSizeOptions: [100, 200, 500],
	});

	//监听变更
	const { el: headerEl, height: headerHeight, onResize } = useResize();

	const location = useLocation();
	const navigate = useNavigate();

	useEffect(() => {
		getPageConfig();
	}, [])

	useEffect(() => {
		queryTableList(1);
	}, [formData])

	useEffect(() => {
		queryTableList();
	}, [pages.current, pages.pageSize])

	//获取页面的配置信息
	const getPageConfig = async () => {
		setLoading(true);
		const params = {
			code: pageCode,
		}
		const { success, data = {} } = await getFieldConfig(params);
		if (success) {
			const { param = '' } = data;
			if (param) {
				setPageConfig(JSON.parse(param));
			}
		}
		setLoading(false)
	}

	//更新配置文件
	const updatePageConfig = async (keys, val, cb) => {
		const obj = {
			...pageConfig,
			[keys]: val
		}
		const { success } = await updateFieldConfig({
			code: pageCode,
			param: JSON.stringify(obj)
		});
		if (success) {
			setPageConfig(obj);
		}
		cb && cb(success);
	}

	//获取售后单列表
	const queryTableList = async (current) => {
		setLoading(true);
		const params = {
			...formData,
			orderBy,
			sortBy: orderBy == 'applyTime' ? 'desc' : 'asc',
			pageCurrent: current || pages.current,
			pageSize: pages.pageSize,
		}
		if (location.state && location.state.orderSn) {
			params.orderSn = [location.state.orderSn];
		}
		const { success, data } = await getAfterSalesList(params);
		if (success) {
			const { records, total } = data;
			setPages({
				...pages,
				current: current || pages.current,
				total: total
			})
			setTableList(records);
			setselectKeys([]);
		}
		setLoading(false)
	}

	/**
	 * 更换数据
	 * @param {*} arr 更新后的订单数组
	 * @param {*} isCount //是否需要请求统计信息，默认不用1，需要2
	 */
	const replaceData = (arr) => {
		//做出处理
		const arr1 = [...tableList];
		//先判断状态是否进行流转
		for (let i in arr) {
			const item = arr[i];
			const index = findIndex(arr1, ['id', item.id]);
			arr1[index] = item;
		}
		setTableList(arr1);
	};

	//接口级别更新数据,局部刷新
	const handleGetData = async (ids) => {
		setLoading(true);
		const { data, success } = await getAfterSalesListById(ids || selectKeys);
		if (success) {
			replaceData(data);
		}
		setLoading(false);
	};

	//订单操作后处理
	const handleOk = (updateType = 1, data) => {
		//操作成功之后更新菜单信息
		if (updateType == 1) {
			handleGetData(data);
		} else if (updateType == 2) {
			queryTableList();
		}
	}

	//菜单信息
	const AcitonProps = {
		pageConfig,
		formData,
		selectKeys,
		tableList,
		handleOk,
		setLoading,
		updatePageConfig
	}

	//右侧操作区
	const RightActionProps = {
		initColumns,
		realColumns: pageConfig.columns,
		orderBy,
		setOrderBy,
		updatePageConfig,
	}

	//表格区域
	const TableListProps = {
		tableList,
		selectKeys,
		realColumns: pageConfig.columns,
		headerHeight: headerHeight + 52,
		setselectKeys,
		handleOk,
		updatePageConfig,
		triggerSearchCb(value){
      setFormData(value);
		}
	}

	//分页数据
	const pageProps = {
		pagination: pages,
		selectTotal: selectKeys.length,
		handleChange(current, size) {
			const obj = { ...pages, current, pageSize: size };
			setPages(obj);
		},
	};
	
	const searchContentProps = {
		formData,
		orderBy,
		onResize,
		handleSearch(val){
			if (location.state && location.state.orderSn) {
				val.orderSn = [location.state.orderSn];
				navigate('/views/afterSales/salesOrder', { replace: true });
			}
			setFormData(val);
		}
	}

	return (
		<div className='zjf-container-nof'>
			<Alert style={{ marginBottom: '16px' }} showIcon type='info' message="注：1、目前只支持淘宝、京东、抖音、拼多多平台的售后单同步，每3分钟自动同步；（平台开头的数据均为三方平台的数据）" />
			<div ref={headerEl} className={styles.table_header} >
	      <SearchContent {...searchContentProps} />
				<HeaderActions {...AcitonProps} />
				<RightAction {...RightActionProps} />
			</div>
			<TableList {...TableListProps} />
			<div className={styles.footerInfo}>
				<CommonPagination {...pageProps} />
			</div>
			<CommonLoading loading={loading} />
		</div>
	);
};

export default SalesOrder;
